import ApiV1WxSessionSave_post from "@/api/ApiV1WxSessionSave_post";
import type { IRawSession } from "@/chatlog_types/IRawSession";
import dayjs from "dayjs";
import type { ITask } from "../tasks";
import { TaskType, type ITaskTypeDataMap } from "../tasks/TaskType";
import { sessions_forage } from "./SessionsMgr";

export function create_session_commit_job(raw: IRawSession): ITask<TaskType.Session, IRawSession> {
  const job = {
    id: `session_${raw.account}_${raw.userName}`,
    title: `提交${raw.account}的会话`,
    desc: `用户名: ${raw.userName} ` +
      `昵称: ${raw.nickName} ` +
      `时间：${dayjs(raw.nTime).format('YYYY-MM-DD HH:mm:ss')}` +
      `内容：${raw.content} `,
    data: raw,
    type: TaskType.Session as const,
    run: async () => {
      const key = `session_item##${raw.account}##${raw.userName}`;
      /*
      step0. 查看"本地数据"是否"不存在或有差异"
      step1. 提交数据至服务端
      step2. 完成提交，记录在"本地数据"
      */
      const body: ApiV1WxSessionSave_post.BodyParams = {
        ...raw,
        order: raw.nOrder,
        time: dayjs(raw.nTime).format('YYYY-MM-DD HH:mm:ss'),
      };
      return ApiV1WxSessionSave_post.call(body).then(() => {
        return sessions_forage.setItem(key, raw);
      });
    }
  };


  return job;
}
